import * as React from 'react'
import { connect } from 'react-redux'
import history from './history'
function requireAuthentication(Component: any) {
  if (Component.AuthenticatedComponent) {
    return Component.AuthenticatedComponent
  }
  class AuthenticatedComponent extends React.Component<any, any> {
    state = {
      login: true,
    }
    componentWillMount() {
      this.checkAuth();
    }
    componentWillReceiveProps(nextProps: any) {
      this.checkAuth()
    }
    checkAuth() {
      const token = this.props.token
      const login = token ? true : false
      if (!login) {
        let redirect = this.props.location.pathname + this.props.location.search
        history.push('/login?message=401&redirect_uri=' + encodeURIComponent(redirect))
        return
      }
      this.setState({ login })
    }
    render() {
      if (this.state.login) {
        return <Component {...this.props}/>
      }
      return ''
    }
  }
  function mapStateToProps(state: any) {
    return {
     token: state.user.token,
    }
   }
   function mapDispatchToProps(dispatch: any) {
    return {}
   }
   Component.AuthenticatedComponent = connect(mapStateToProps, mapDispatchToProps)(AuthenticatedComponent)
   return Component.AuthenticatedComponent
}

export default requireAuthentication